package com.rykj.energy.basic.rest;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.rykj.energy.common.enums.DeviceTypes;
import com.rykj.energy.common.enums.ExceptionCode;
import com.rykj.energy.common.enums.ResponseEnum;
import com.rykj.energy.common.utils.CollectionUtils;
import com.rykj.energy.common.utils.DES;
import com.rykj.energy.common.utils.Result;
import com.rykj.energy.common.utils.StringUtils;
import com.rykj.energy.database.pojo.BasicCamera;
import com.rykj.energy.database.pojo.BasicCameraPresetting;
import com.rykj.energy.database.pojo.BasicDevice;
import com.rykj.energy.database.pojo.BusinessCameraObject;
import com.rykj.energy.database.pojo.vo.DeviceVo;
import com.rykj.energy.database.pojo.vo.OrganizationVO;
import com.rykj.energy.database.pojo.vo.VBasicCameraView;
import com.rykj.energy.database.service.ICameraObjectService;
import com.rykj.energy.database.service.ICameraPresettingService;
import com.rykj.energy.database.service.ICameraService;
import com.rykj.energy.database.service.IDeviceSercive;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import net.anumbrella.seaweedfs.core.file.FileHandleStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@Api(tags = "摄像头设备管理")
@Slf4j
@RestController
//@DependsOn("springUtil")
@RequestMapping("/device")
public class DeviceCameraController {

    @Autowired
    private ICameraService cameraService;

    @Autowired
    private IDeviceSercive deviceSercive;

    @Autowired
    private ICameraPresettingService cameraPresetService;

    @Autowired
    private ICameraObjectService cameraObjectService;

    @ApiOperation("新增摄像头(添加设备)")
    @PostMapping("/camera/addDevOrCamera")
    public Result addDeviceCamera(@RequestBody DeviceVo deviceVo){
        try{
            if(StringUtils.isNotEmpty(deviceVo.getDevPwd())){
                deviceVo.setDevPwd(new DES().decode(deviceVo.getDevPwd()));
            }
            //NVR设备添加
            if(DeviceTypes.NVR.getCode().equals(deviceVo.getDevType())){
                BasicDevice device = new BasicDevice();
                //vo转换成设备对象
                deviceSercive.getVoToDevice(deviceVo,device);
                //摄像头校验
                Result checkRest= deviceSercive.checkDevice(device);
                if(!checkRest.isSuccess()){
                    return checkRest;
                }
                List<BasicCamera>  nvrCameras = deviceSercive.addDevice(device);
                    //把NVR下的摄像头返回
                return Result.success(nvrCameras);
            }else {
                //摄像头添加
                BasicCamera camera = new BasicCamera();
                //vo转换成摄像头对象
                cameraService.getVoToCamera(deviceVo,camera);
                //摄像头校验
                Result checkRest= cameraService.checkCamera(camera);
                if(!checkRest.isSuccess()){
                    return checkRest;
                }
                camera  = cameraService.addCamera(camera,deviceVo.getPresetting());
                return Result.success("创建成功",camera);
            }
        }catch (Exception e){
            log.error("创建失败",e);
            return  Result.failure(e.getMessage());
        }
    }

    @ApiOperation("批量保存摄像头")
    @PostMapping("/camera/saveCameras")
    public Result saveCameras(@RequestBody List<BasicCamera> cameras ) {
        try {
            log.info("批量保存摄像头");
            for (BasicCamera ca : cameras){
                if(StringUtils.isNotEmpty(ca.getCamAlias())){
                    List<BasicCamera> list = cameraService.findByChannelAlias(ca.getCamAlias());
                    if(list!=null && list.size()>0){
                        return Result.failure( ExceptionCode.CAMERA_NAME_IS_EXISTENCE.getMessage()+":"+ca.getCamAlias());
                    }
                }
            }
            if(cameras.size()>1){
                for (int i=0;i<cameras.size();i++){
                    BasicCamera cai = cameras.get(i);
                    for (int j=i+1;j<cameras.size();j++){
                        BasicCamera caj = cameras.get(j);
                        if(cai.getCamAlias().equals(caj.getCamAlias())){
                            return Result.failure( ExceptionCode.CAMERA_NAME_IS_REPEAT.getMessage()+":"+caj.getCamAlias());
                        }
                    }
                }
            }
            cameraService.saveCameras(cameras);

            return  Result.success("批量保存摄像头成功",null);
        } catch (Exception e) {
            log.error("批量保存摄像头失败", e);
            return  Result.failure("创建失败，请检查信息是否有误;"+e.getMessage());
        }
    }


    @ApiOperation("删除设备摄像头")
    @GetMapping("/camera/delete/{devId}")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "devId", paramType = "path", value = "摄像头Id", required = true),
            @ApiImplicitParam(name = "devType", value = "设备类型", paramType = "query")
    })
    public Result delete(@PathVariable("devId") int devId,
                         @RequestParam(value = "devType",required = false) String devType ) {
        try {
            //如果是设备，直接删除设备及下面的摄像头
            if(DeviceTypes.NVR.getCode().equals(devType)){
                 deviceSercive.deleteDevCamera(devId);
            }else {
                //直接删除摄像头
                cameraService.deleteCamera(devId);
            }
            return Result.success("删除成功",null);
        } catch (Exception e) {
            log.error("删除失败", e);
            return Result.failure(e.getMessage());
        }
    }

    @ApiOperation("修改摄像头信息")
    @PostMapping("/camera/update")
    public Result update(@RequestBody DeviceVo deviceCameraVo) {
        try {
            if(StringUtils.isNotEmpty(deviceCameraVo.getDevPwd())){
                deviceCameraVo.setDevPwd(new DES().decode(deviceCameraVo.getDevPwd()));
            }
            //NVR设备修改
            if(DeviceTypes.NVR.getCode().equals(deviceCameraVo.getDevType())){
                BasicDevice device = new BasicDevice();
                //vo转换成设备对象
                deviceSercive.getVoToDevice(deviceCameraVo,device);
                //设备校验
                Result checkRest= deviceSercive.checkDevice(device);
                if(!checkRest.isSuccess()){
                    return checkRest;
                }
               List<BasicCamera> nvrCameras= deviceSercive.updateDevice(device);
               //把NVR下的摄像头返回
               return Result.success(nvrCameras);
            }else {
                //摄像头添加
                BasicCamera camera = new BasicCamera();
                //vo转换成摄像头对象
                cameraService.getVoToCamera(deviceCameraVo,camera);
                //摄像头校验
                Result checkRest= cameraService.checkCamera(camera);
                if(!checkRest.isSuccess()){
                    return checkRest;
                }
                if(DeviceTypes.RTSP.getCode().equals(camera.getDevType())){
                    camera.setCamIndex(0);
                }else if(StringUtils.isEmpty(camera.getCamIndex())){
                    camera.setCamIndex(1);
                }
                cameraService.updateCamera(camera,deviceCameraVo.getPresetting());
                return Result.success("修改成功",null);
            }
        } catch (Exception e) {
            log.error("编辑设备摄像头失败", e);
            return  Result.failure(e.getMessage());
        }
    }

    @ApiOperation("获取区域及摄像头树-树形结构")
    @GetMapping("/camera/getOrgCameras")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orgId", value = "区域id",  paramType = "query"),
            @ApiImplicitParam(name = "searchName", value = "摄像头名称（模糊匹配）", paramType = "query"),
    })
    public Result<List<OrganizationVO>> getOrgCameras(@RequestParam(value="orgId",required = false) Integer orgId ,
                                                      @RequestParam(value="searchName",required = false) String searchName ) {
        try {
            List<OrganizationVO> list = deviceSercive.getOrgCameras(orgId,searchName);
            return Result.success(list);
        } catch (Exception e) {
            log.error("获取区域下的摄像头列表", e);
            return Result.failure(ResponseEnum.FAILED.getCode(), e.getMessage());
        }
    }


    @ApiOperation("获取组织下的摄像头列表-分页（递归子组织）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "当前页数", required = true, paramType = "path"),
            @ApiImplicitParam(name = "pageSize", value = "显示条数", required = true, paramType = "path"),
            @ApiImplicitParam(name = "orgId", value = "区域id",  paramType = "query"),
            @ApiImplicitParam(name = "searchName", value = "摄像头名称（模糊匹配）", paramType = "query"),
            @ApiImplicitParam(name = "searchIp", value = "摄像头Ip", paramType = "query"),
            @ApiImplicitParam(name = "devType", value = "设备类型，nvr、rtsp、camera", paramType = "query")
    })
    @GetMapping("/camera/getCamerasByOrgId/{pageNum}/{pageSize}")
    public Result<IPage<DeviceVo> > getCamerasByOrgId(@PathVariable("pageNum")Integer pageNum,
                                                      @PathVariable("pageSize")Integer pageSize,
                                                      @RequestParam(value="orgId",required = false) Integer orgId,
                                                      @RequestParam(value = "searchName",required = false) String searchName ,
                                                      @RequestParam(value = "searchIp",required = false) String searchIp,
                                                      @RequestParam(value = "devType",required = false) String devType) {
        try {
            IPage<DeviceVo> page=null;
            page = deviceSercive.getCamerasByOrgId(pageNum,pageSize,orgId,searchName,searchIp,devType);
            return   Result.success(page);
        } catch (Exception e) {
            log.error("获取区域下的设备摄像头列表异常", e);
            return Result.failure("获取区域下的设备摄像头列表异常");
        }
    }



    @ApiOperation("获取组织下的摄像头-预置位-分页列表（递归子组织）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "当前页数", required = true, paramType = "path"),
            @ApiImplicitParam(name = "pageSize", value = "显示条数", required = true, paramType = "path"),
            @ApiImplicitParam(name = "orgId", value = "区域id",  paramType = "query"),
            @ApiImplicitParam(name = "searchName", value = "摄像头或预置位名称（模糊匹配）", paramType = "query"),
            @ApiImplicitParam(name = "searchIp", value = "摄像头Ip", paramType = "query"),
            @ApiImplicitParam(name = "devType", value = "设备类型，nvr、rtsp、camera", paramType = "query")
    })
    @GetMapping("/camera/getCameraAndPresetByOrgId/{pageNum}/{pageSize}")
    public Result<IPage<VBasicCameraView> > getCameraAndPresetByOrgId(@PathVariable("pageNum")Integer pageNum,
                                                                      @PathVariable("pageSize")Integer pageSize,
                                                                      @RequestParam(value="orgId",required = false) Integer orgId,
                                                                      @RequestParam(value = "searchName",required = false) String searchName ,
                                                                      @RequestParam(value = "searchIp",required = false) String searchIp,
                                                                      @RequestParam(value = "devType",required = false) String devType) {
        try {
            IPage<VBasicCameraView> page=null;
            page = deviceSercive.getCameraAndPresetByOrgId(pageNum,pageSize,orgId,searchName,searchIp,devType);
            return   Result.success(page);
        } catch (Exception e) {
            log.error("获取组织下的摄像头-预置位-分页列表异常", e);
            return Result.failure("获取组织下的摄像头-预置位-分页列表异常");
        }
    }



    @ApiOperation("刷新摄像头现场画面")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "cameraId", value = "摄像头id", required = true, paramType = "path"),
    })
    @GetMapping("/camera/getFreshCameraImg/{cameraId}")
    public Result getFreshCameraImg(@PathVariable("cameraId") Integer cameraId){
        try {
            BasicCamera camera = cameraService.findById(cameraId);
            FileHandleStatus fileHandle= cameraService.getCameraImg(camera);
            if(null==fileHandle){
                return Result.failure("获取摄像头现场画面为空");
            }
            camera.setPhotoPath(fileHandle.getFileUrl());
            cameraService.updateCamera(camera,null);
            return   Result.success(camera.getPhotoPath());
        } catch (Exception e) {
            log.error("刷新摄像头现场画面异常", e);
            return Result.failure("刷新摄像头现场画面异常");
        }
    }

    @ApiOperation("新增或修改预置位")
    @PostMapping("/camera/addOrUpdatePreset/{cameraId}")
    public Result addOrUpdatePreset( @PathVariable("cameraId") Integer cameraId,@RequestBody List<BasicCameraPresetting> cameraPresets) {
        try {
            BasicCamera camera =cameraService.findById(cameraId);
            FileHandleStatus fileHandle =null;
            if(CollectionUtils.isNotEmpty(cameraPresets)){
                List<Integer> presetIds =new ArrayList<>();
                for (BasicCameraPresetting cameraPreset:cameraPresets) {
                    cameraPreset.setCameraId(cameraId);
                    cameraPreset.setCameraNo(camera.getCamNo());
                    if(StringUtils.isNotEmpty(cameraPreset.getId())&& !"0".equals(cameraPreset.getId())){
                        presetIds.add(cameraPreset.getId());
                    }
                    if(cameraService.sdkPresetPoint(cameraPreset.getCameraNo(),cameraPreset.getPresettingCode())){
                        //抓取预置位现场画面
                        fileHandle = cameraService.getCameraImg(camera);
                        if(null==fileHandle){
                            throw new Exception("通道id"+cameraPreset.getCameraNo()+"_预置点编号:"+cameraPreset.getPresettingCode()+" 抓取现场画面失败");
                        }
                        cameraPreset.setPreImgPath(fileHandle.getFileUrl());
                    }else {
                        log.error("通道id"+cameraPreset.getCameraNo()+"_预置点编号:"+cameraPreset.getPresettingCode()+" 操作失败");
                       // throw new Exception("通道id"+cameraPreset.getCameraNo()+"_预置点编号:"+cameraPreset.getPresettingCode()+" 操作失败");

                    }
                }
                cameraPresetService.addOrUpdatePreset(cameraId,presetIds,cameraPresets);
            }
            return  Result.success("添加成功",null);
        }catch (Exception e){
            log.error("====添加或修改预置位失败===",e);
            return Result.failure("添加或修改预置位失败");
        }
    }


    @ApiOperation("获取摄像头下的预置位列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "cameraId", value = "摄像头id", required = true, paramType = "path"),
    })
    @GetMapping("/camera/getPresetByCameraId/{cameraId}")
    public Result<List<BasicCameraPresetting> > getPresetByCameraId(@PathVariable("cameraId")Integer cameraId) {
        try {

         List<BasicCameraPresetting> presettings = deviceSercive.getPresetByCameraId(cameraId);
            return   Result.success(presettings);
        } catch (Exception e) {
            log.error("获取摄像头下的预置位列表异常", e);
            return Result.failure("获取摄像头下的预置位列表异常");
        }
    }


    @ApiOperation("获取摄像头绑定检测对象")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "taskId", value = "任务id", required = true, paramType = "path"),
            @ApiImplicitParam(name = "cameraId", value = "摄像头id", required = true, paramType = "path"),
            @ApiImplicitParam(name = "presetId", value = "预置位id", required = true, paramType = "query")
    })
    @GetMapping("/camera/getFreshCameraImg/{taskId}/{cameraId}")
    public Result getCameraObjectById(@PathVariable("taskId") Integer taskId,
                                      @PathVariable("cameraId") Integer cameraId,
                                      @RequestParam(value = "presetId",required = false) Integer presetId ){
        try {
           List<BusinessCameraObject> cameraObjects = cameraObjectService.getCameraObjectById(taskId,cameraId,presetId);
            return   Result.success(cameraObjects);
        } catch (Exception e) {
            log.error("获取摄像头绑定检测对象异常", e);
            return Result.failure("获取摄像头绑定检测对象异常");
        }
    }



    //
//    @ApiOperation("获取摄像头详细信息")
//    @ApiImplicitParam(name = "cameraId", paramType = "path", value = "摄像头Id", required = true)
//    @GetMapping("/info/{cameraId}")
//    public Result<BasicCamera> getInfo(@PathVariable("cameraId") int cameraId) {
//        try {
//            BasicCamera info = cameraService.findById(cameraId);
//            if (info == null) {
//                return Result.failure( ExceptionCode.CAMERA_NOT_EXIST.getMessage());
//            }
//            info.setCamPwd(new DES().encode(info.getCamPwd()));
//            return Result.success(info);
//        } catch (Exception e) {
//            log.error("获取摄像头详细信息失败", e);
//            return Result.failure( e.getMessage());
//        }
//    }
//

    //
//    @ApiOperation("批量删除摄像头")
//    @GetMapping("/deleteBatchCameras")
//    @ApiImplicitParam(name = "channelIds", paramType = "query", value = "摄像头Id,多个逗号隔开", required = true)
//    public Result deleteBatchCameras(@RequestParam("channelIds") String channelIds) {
//        try {
//            String cameraIds[]=channelIds.split(",");
//            for (String cameraId:cameraIds) {
//                ResultDto<Object> resultDto = cameraService.deleteCamera(Integer.valueOf(cameraId));
//                if(!resultDto.isResultStatus()){
//                    return Result.failure(resultDto.getContent());
//                }
//            }
//            return Result.success("批量删除摄像头成功",null);
//        } catch (Exception e) {
//            log.error("批量删除摄像头失败", e);
//            return Result.failure(e.getMessage());
//        }
//    }
//


//
///*    @ApiOperation("获取组织下的摄像头(包括球机预置位)列表-分页（递归子组织）")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "pageNum", value = "当前页数", required = true, paramType = "path"),
//            @ApiImplicitParam(name = "pageSize", value = "显示条数", required = true, paramType = "path"),
//            @ApiImplicitParam(name = "orgId", value = "组织id", required = true, paramType = "path"),
//            @ApiImplicitParam(name = "searchName", value = "摄像头名称（模糊匹配）", paramType = "query"),
//            @ApiImplicitParam(name = "searchIp", value = "摄像头Ip", paramType = "query"),
//            @ApiImplicitParam(name = "devType", value = "摄像头类型", paramType = "query"),
//            @ApiImplicitParam(name = "taskCode", value = "摄像头类型", paramType = "query"),
//            @ApiImplicitParam(name = "orgType",  required = true,value = "nvr:nvr区域,area:真实区域", paramType = "query"),
//            @ApiImplicitParam(name = "noNVR",  value = "1表示不返回NVR设备", paramType = "query")
//    })
//    @GetMapping("/getCamerasViewsByAreaId/{pageNum}/{pageSize}/{orgId}")
//    public Result getCamerasViewsByAreaId(@PathVariable("pageNum")Integer pageNum,
//                                     @PathVariable("pageSize")Integer pageSize,
//                                     @PathVariable("orgId") Integer orgId,
//                                     @RequestParam(value = "searchName",required = false) String searchName ,
//                                     @RequestParam(value = "searchIp",required = false) String searchIp,
//                                     @RequestParam(value = "org
//                                     Type",required = false) String orgType,
//                                     @RequestParam(value = "taskCode",required = false) String taskCode,
//                                     @RequestParam(value = "devType",required = false) String devType,
//                                     @RequestParam(value = "noNVR",required = false) String noNVR
//    ) {
//        try {
//            Page<VBasicCameraView> cameras = cameraService.getCamerasViewByAreaId(pageNum,pageSize,orgId,searchName,searchIp,orgType,noNVR,devType,taskCode);
//
//            return   Result.success(cameras);
//        } catch (Exception e) {
//            log.error("获取区域下的摄像头列表", e);
//            return Result.failure( e.getMessage());
//        }
//    }*/
//





//
//
//
//
//  /*  @ApiOperation("获取组织下的摄像头列表-不分页（递归子组织）")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "orgId", value = "组织id ", required = true, paramType = "path")
//    })
//    @GetMapping("/getCamByOrgId/{orgId}")
//    public Result getCamByOrgId(@PathVariable("orgId") Integer orgId) {
//        try {
//            List<BasicCamera> cameras = cameraService.getCamerasByOrgId(orgId,"yes");
//            return Result.success(cameras);
//        } catch (Exception e) {
//            log.error("获取区域下的摄像头列表", e);
//            return Result.failure( e.getMessage());
//        }
//    }*/
//
//    @ApiOperation("获取非当前仪表关联的摄像头")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "orgId", value = "组织id", required = true, paramType = "path"),
//            @ApiImplicitParam(name = "searchName", value = "摄像头名称（模糊匹配）", paramType = "query"),
//            @ApiImplicitParam(name = "searchIp", value = "摄像头Ip", paramType = "query"),
//            @ApiImplicitParam(name = "devType", value = "摄像头类型", paramType = "query"),
//            @ApiImplicitParam(name = "meterId", value = "仪表id", paramType = "query")
//    })
//    @GetMapping("/getCamerasByMeterId/{orgId}")
//    public Result<List<BasicCamera>> getCamerasByMeterId(
//                                     @PathVariable("orgId") Integer orgId,
//                                     @RequestParam(value = "searchName",required = false) String searchName ,
//                                     @RequestParam(value = "searchIp",required = false) String searchIp,
//                                     @RequestParam(value = "devType",required = false) String devType,
//                                     @RequestParam(value = "meterId",required = false) Integer meterId) {
//        try {
//            List<BasicCamera> cameras = cameraService.getCamerasByMeterId(orgId,searchName,searchIp,devType,meterId);
//            return   Result.success(cameras);
//        } catch (Exception e) {
//            log.error("获取非当前仪表关联的摄像头异常", e);
//            return Result.failure("获取非当前仪表关联的摄像头异常");
//        }
//    }
//
//
//

//
//
//    @ApiOperation("获取任务下摄像头列表-分页（递归子组织）")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "pageNum", value = "当前页数", required = true, paramType = "path"),
//            @ApiImplicitParam(name = "pageSize", value = "显示条数", required = true, paramType = "path"),
//            @ApiImplicitParam(name = "orgId", value = "组织id", required = true, paramType = "path"),
//            @ApiImplicitParam(name = "searchName", value = "摄像头名称（模糊匹配）", paramType = "query"),
//            @ApiImplicitParam(name = "searchIp", value = "摄像头Ip", paramType = "query"),
//            @ApiImplicitParam(name = "devType", value = "摄像头类型", paramType = "query")
//    })
//    @GetMapping("/getCamerasTasks/{pageNum}/{pageSize}/{orgId}")
//    public Result<IPage<CamreaTasksVo> > getCamerasTasks(@PathVariable("pageNum")Integer pageNum,
//                                                         @PathVariable("pageSize")Integer pageSize,
//                                                         @PathVariable("orgId") Integer orgId,
//                                                         @RequestParam(value = "searchName",required = false) String searchName ,
//                                                         @RequestParam(value = "searchIp",required = false) String searchIp,
//                                                         @RequestParam(value = "devType",required = false) String devType) {
//        try {
//            IPage<CamreaTasksVo> page=null;
//            page = deviceSercive.getCamerasTasks(pageNum,pageSize,orgId,searchName,searchIp,devType);
//            return   Result.success(page);
//        } catch (Exception e) {
//            log.error("获取任务下摄像头列表异常", e);
//            return Result.failure("获取任务下摄像头列表异常");
//        }
//    }



}
